﻿using SharpDepend.Datatypes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SharpDepend.Classes
{
    public class Font
    {
        public string FontName { get; set; }
        public Dictionary<char, List<Vector2>> Chars { get; set; }
    }

    public class FontReader
    {
        public Font LoadFont(Stream stream)
        {
            stream.Position = 0;

            float sfntVersion = ReadFixed(stream);
            ushort numTables = ReadUShort(stream);
            ushort searchRange = ReadUShort(stream);
            ushort entrySelector = ReadUShort(stream);
            ushort rangeShift = ReadUShort(stream);

            HashSet<string> tags = new HashSet<string>();

            for (int i = 0; i < numTables; i++)
            {
                ulong tag = ReadULong(stream);
                string tagName = UTF8Encoding.UTF8.GetString(BitConverter.GetBytes(tag), 0, 4);
                ulong checkSum = ReadULong(stream);
                ulong offset = ReadULong(stream);
                ulong length = ReadULong(stream);

                tags.Add(tagName);

                if (tagName.Equals("name"))
                {

                }
            }

            return null;
        }

        float ReadFixed(Stream stream)
        {
            ushort left = ReadUShort(stream);
            ushort right = ReadUShort(stream);

            float result = left + (right) / ushort.MaxValue;

            return result;
        }

        ushort ReadUShort(Stream stream)
        {
            byte[] s = new byte[2];
            stream.Read(s, 0, s.Length);
            Array.Reverse(s);
            return (ushort)BitConverter.ToInt16(s, 0);
        }
        uint ReadUInt(Stream stream)
        {
            byte[] s = new byte[4];
            stream.Read(s, 0, s.Length);
            Array.Reverse(s);
            return (uint)BitConverter.ToInt32(s, 0);
        }
        uint ReadULong(Stream stream)
        {
            return ReadUInt(stream);
        }
    }
}
